/*
 * Created on 2006-8-9 ����06:25:17
 */
package cn.com.sbell.vss.csg.vsclient.dahua;

import java.io.IOException;
import java.io.StringReader;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import cn.com.sbell.vss.VssConstants;
import cn.com.sbell.vss.VssException;
import cn.com.sbell.vss.csg.vap.bean.AHInfo;
import cn.com.sbell.vss.csg.vap.bean.AlarmConfiguration;
import cn.com.sbell.vss.csg.vap.bean.CameraHide;
import cn.com.sbell.vss.csg.vap.bean.CruisePointInfo;
import cn.com.sbell.vss.csg.vap.bean.CruiseTrackInfo;
import cn.com.sbell.vss.csg.vap.bean.DeviceInfo;
import cn.com.sbell.vss.csg.vap.bean.DeviceStatistic;
import cn.com.sbell.vss.csg.vap.bean.DiskSizeInfo;
import cn.com.sbell.vss.csg.vap.bean.GPIODeviceInfo;
import cn.com.sbell.vss.csg.vap.bean.ImageAdjustingInfo;
import cn.com.sbell.vss.csg.vap.bean.ImageParameterInfos;
import cn.com.sbell.vss.csg.vap.bean.LocalStorageTask;
import cn.com.sbell.vss.csg.vap.bean.LogInfo;
import cn.com.sbell.vss.csg.vap.bean.LogRequest;
import cn.com.sbell.vss.csg.vap.bean.NetManageInfo;
import cn.com.sbell.vss.csg.vap.bean.NetworkCfgIn;
import cn.com.sbell.vss.csg.vap.bean.NetworkCfgOut;
import cn.com.sbell.vss.csg.vap.bean.PTZRegress;
import cn.com.sbell.vss.csg.vap.bean.PresetPTZ;
import cn.com.sbell.vss.csg.vap.bean.PtzCommander;
import cn.com.sbell.vss.csg.vap.bean.RecordFile;
import cn.com.sbell.vss.csg.vap.bean.RecordSchedule;
import cn.com.sbell.vss.csg.vap.bean.Schedule;
import cn.com.sbell.vss.csg.vap.bean.SerialPortInfo;
import cn.com.sbell.vss.csg.vap.bean.StorageQuery;
import cn.com.sbell.vss.csg.vap.bean.TimeInfo;
import cn.com.sbell.vss.csg.vap.bean.TransparentChannelInfo;
import cn.com.sbell.vss.csg.vap.bean.UploadPic;
import cn.com.sbell.vss.csg.vap.bean.UserInfo;
import cn.com.sbell.vss.csg.vap.bean.VSCommon;
import cn.com.sbell.vss.csg.vap.bean.VideoFormat;
import cn.com.sbell.vss.csg.vap.bean.VideoInfo;
import cn.com.sbell.vss.csg.vap.bean.VideoPerformance;
import cn.com.sbell.vss.csg.vap.bean.CameraHide.HideImageArea;
import cn.com.sbell.vss.csg.vap.bean.DeviceStatistic.DiskStatistic;
import cn.com.sbell.vss.csg.vap.bean.DeviceStatistic.VideoChannelStatistic;
import cn.com.sbell.vss.csg.vap.bean.GPIODeviceInfo.ChannelInfo;
import cn.com.sbell.vss.csg.vap.bean.ImageParameterInfos.ImageParameterInfo;
import cn.com.sbell.vss.csg.vap.bean.NetworkCfgOut.Ethernet;
import cn.com.sbell.vss.csg.vsclient.AbstractVsClient;
import cn.com.sbell.vss.csg.vsclient.AccessInfo;
import cn.com.sbell.vss.csg.vsclient.VsUpgradeThread;
import cn.com.sbell.vss.csg.vsclient.util.BeanValidator;
import cn.com.sbell.vss.csg.vsclient.util.CSGConfiguration;

public class DaHuaVsClient extends AbstractVsClient {
	private static final Log log = LogFactory.getLog(DaHuaVsClient.class);

	private HttpClient httpClient;

	private int statusCode = 0;

	private static final String RETURN_CODE_PATH = "/response/result/@code";

	private static final String PARAMETERS_PATH = "/response/parameters";

	private static final String SUCCESS_CODE = "0";

	public static void main(String[] args) {
		HttpClient client = new HttpClient();
		HostConfiguration hostConfig = new HostConfiguration();
		hostConfig.setHost(new HttpHost("192.168.6.149", 80));
		client.setHostConfiguration(hostConfig);
		SimpleHttpConnectionManager shcm = new SimpleHttpConnectionManager();
		HttpConnectionManagerParams hcmp = new HttpConnectionManagerParams();
		hcmp.setConnectionTimeout(5000);
		hcmp.setDefaultMaxConnectionsPerHost(1);
		hcmp.setLinger(1);
		hcmp.setMaxTotalConnections(1);
		hcmp.setSoTimeout(10000);
		shcm.setParams(hcmp);
		client.setHttpConnectionManager(shcm);
		client.getParams().setContentCharset(VssConstants.DEFAULT_ENCODINIG);
		GetMethod method = new GetMethod("/GetVsPerformance");
		
		method.setQueryString(new NameValuePair[] {
				//common param
				new NameValuePair("vsLoginUsername", "admin"),
				new NameValuePair("vsLoginPassword", "admin"),
				new NameValuePair("vsVendor", "dahua"),
				new NameValuePair("vsProductVersion", ""),
				new NameValuePair("vsSoftwareVersion", ""),
				new NameValuePair("vsDeviceId", "090110000103520001"),
				new NameValuePair("userId", "7147B67E2D29FE74A4311C9357B7A408"),
				new NameValuePair("__username", "root"),
				new NameValuePair("__password", "e10adc3949ba59abbe56e057f20f883e"),
				new NameValuePair("route", ""),
				new NameValuePair("locale", ""),
				//special param
				new NameValuePair("statisticTarget", "CPU,MEM,DISK")
		});

		Document doc = null;
		try {
			int statusCode = client.executeMethod(method);
			if (statusCode == 401) {
				throw new VssException(VssConstants.CODE_VS_AUTHENTICATE_FAILED);
			}
			SAXReader reader = new SAXReader();
			doc = reader.read(method.getResponseBodyAsStream());
		} catch (IOException e) {
			throw new VssException(VssConstants.CODE_VISIT_NVS_ERROR);
		} catch (DocumentException e) {
			throw new VssException(VssConstants.CODE_VS_RETURN_ERROR_RESULT);
		} finally {
			method.releaseConnection();
		}
		System.out.println(doc.toString());
	}

	public DaHuaVsClient(AccessInfo access) {
		super(access);
		httpClient = new HttpClient();
		HostConfiguration hostConfiguration = new HostConfiguration();
		hostConfiguration.setHost(new HttpHost(access.vsIp, access.vsPort
				.intValue()));
		httpClient.setHostConfiguration(hostConfiguration);
		SimpleHttpConnectionManager shcm = new SimpleHttpConnectionManager();
		HttpConnectionManagerParams hcmp = new HttpConnectionManagerParams();
		hcmp.setConnectionTimeout(CSGConfiguration.PU_CONNECTION_TIMEOUT);
		hcmp.setDefaultMaxConnectionsPerHost(1);
		hcmp.setLinger(CSGConfiguration.PU_SO_LINGER);
		hcmp.setMaxTotalConnections(1);
		hcmp.setSoTimeout(CSGConfiguration.PU_SO_TIMEOUT);
		shcm.setParams(hcmp);
		httpClient.setHttpConnectionManager(shcm);
		httpClient.getParams()
				.setContentCharset(VssConstants.DEFAULT_ENCODINIG);
	}

	public void close() {
		org.apache.commons.httpclient.HttpConnectionManager hcm = httpClient
				.getHttpConnectionManager();
		org.apache.commons.httpclient.HostConfiguration hc = httpClient
				.getHostConfiguration();
		hcm.getConnection(hc).close();
	}

	public boolean controlPtz(PtzCommander ptzCmder) {

		GetMethod method = new GetMethod("/ControlPTZ");
		method.setQueryString(new NameValuePair[] {
				new NameValuePair("ptzId", ptzCmder.getPtzId().toString()),
				new NameValuePair("cmd", ptzCmder.getCmd()),
				new NameValuePair("param", ptzCmder.getParam()),
				new NameValuePair("speed", ptzCmder.getSpeed().toString()),
				new NameValuePair("protocol", ptzCmder.getProtocol()) });

		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean controlVs(int action) {

		GetMethod method = new GetMethod("/ControlVs");
		method.setQueryString(new NameValuePair[] { new NameValuePair("action",
				String.valueOf(action)) });
		excuteMethod(method);
		return true;

	}

	public boolean deleteUser(String username) {

		GetMethod method = new GetMethod("/DeleteVsUser");
		NameValuePair[] pairs = new NameValuePair[] { new NameValuePair("name",
				username) };
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public AccessInfo getAccessInfo() {
		return this.access;
	}

	public SerialPortInfo getDecoderCfg(int channel) {

		GetMethod method = new GetMethod("/GetVsSerialPort");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("port", "2"),
				new NameValuePair("videoId", String.valueOf(channel)) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);

		SerialPortInfo serialPort = new SerialPortInfo();
		serialPort.setPort(getInteger(parameters, "port"));
		serialPort.setBaudRate(getInteger(parameters, "baudRate"));
		serialPort.setDataBit(getInteger(parameters, "dataBit"));
		serialPort.setDecoderAddress(getInteger(parameters, "decoderAddress"));
		serialPort.setDecoderType(getInteger(parameters, "decoderType"));
		serialPort.setFlowcontrol(getInteger(parameters, "flowcontrol"));
		serialPort.setParity(getInteger(parameters, "parity"));
		serialPort.setStopBit(getInteger(parameters, "stopBit"));
		serialPort.setVideoId(getInteger(parameters, "videoId"));
		serialPort.setMode(getString(parameters, "mode"));
		return serialPort;

	}

	public ImageAdjustingInfo getImageAdjustingInfo(int videoId) {

		GetMethod method = new GetMethod("/GetVsImageAdjusting");
		NameValuePair[] pairs = new NameValuePair[] { new NameValuePair(
				"videoId", String.valueOf(videoId)) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);

		ImageAdjustingInfo imgInfo = new ImageAdjustingInfo();
		imgInfo.setBright(getInteger(parameters, "bright"));
		imgInfo.setContrast(getInteger(parameters, "contrast"));
		imgInfo.setHue(getInteger(parameters, "hue"));
		imgInfo.setSaturation(getInteger(parameters, "saturation"));
		imgInfo.setVideoId(getInteger(parameters, "videoId"));

		return imgInfo;
	}

	public VideoFormat getImageFormat(int videoId) {

		GetMethod method = new GetMethod("/GetVsImageFormat");
		NameValuePair[] pairs = new NameValuePair[] { new NameValuePair(
				"videoId", String.valueOf(videoId)) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);

		VideoFormat fmt = new VideoFormat();
		fmt.setMode(getString(parameters, "mode"));
		return fmt;
	}

	public ImageParameterInfos getImageParameterInfo(int videoId) {

		GetMethod method = new GetMethod("/GetVsImageParameters");
		NameValuePair[] pairs = new NameValuePair[] { new NameValuePair(
				"videoId", String.valueOf(videoId)) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);

		ImageParameterInfo netInfo = new ImageParameterInfo();
		netInfo.setBitRate(getInteger(parameters, "net/bitRate"));
		netInfo.setBitRateType(getInteger(parameters, "net/bitRateType"));
		netInfo.setFlag(getInteger(parameters, "net/flag"));
		netInfo.setFrameRate(getInteger(parameters, "net/frameRate"));
		netInfo.setImageSize(getString(parameters, "net/imageSize"));
		netInfo.setPicQuality(getInteger(parameters, "net/picQuality"));
		netInfo.setVideoId(getInteger(parameters, "net/videoId"));
		netInfo.setIFrameInterval(getInteger(parameters, "net/iFrameInterval"));
		netInfo.setStreamType(getInteger(parameters, "net/streamType"));
		ImageParameterInfo recInfo = new ImageParameterInfo();
		recInfo.setBitRate(getInteger(parameters, "rec/bitRate"));
		recInfo.setBitRateType(getInteger(parameters, "rec/bitRateType"));
		recInfo.setFlag(getInteger(parameters, "rec/flag"));
		recInfo.setFrameRate(getInteger(parameters, "rec/frameRate"));
		recInfo.setImageSize(getString(parameters, "rec/imageSize"));
		recInfo.setPicQuality(getInteger(parameters, "rec/picQuality"));
		recInfo.setVideoId(getInteger(parameters, "rec/videoId"));
		recInfo.setIFrameInterval(getInteger(parameters, "rec/iFrameInterval"));
		recInfo.setStreamType(getInteger(parameters, "rec/streamType"));
		ImageParameterInfos infos = new ImageParameterInfos();
		infos.setNets(new ImageParameterInfo[] { netInfo });
		infos.setRec(recInfo);

		return infos;
	}

	public ImageParameterInfos getImageParameterInfo_3N(int videoId) {

		GetMethod method = new GetMethod("/GetVsImageParameters");
		NameValuePair[] pairs = new NameValuePair[] { new NameValuePair(
				"videoId", String.valueOf(videoId)) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);

		ImageParameterInfos infos = new ImageParameterInfos();
		List list = parameters.selectNodes("net");
		if (list != null) {
			ImageParameterInfo[] netInfos = new ImageParameterInfo[list.size()];
			for (int i = 0; i < netInfos.length; i++) {
				Node netNode = (Node) list.get(i);
				ImageParameterInfo netInfo = new ImageParameterInfo();
				netInfo.setBitRate(getInteger(netNode, "bitRate"));
				netInfo.setBitRateType(getInteger(netNode, "bitRateType"));
				netInfo.setFlag(getInteger(netNode, "flag"));
				netInfo.setSubStreamId(getInteger(netNode, "subStreamId"));
				netInfo.setFrameRate(getInteger(netNode, "frameRate"));
				netInfo.setImageSize(getString(netNode, "imageSize"));
				netInfo.setPicQuality(getInteger(netNode, "picQuality"));
				netInfo.setVideoId(getInteger(netNode, "videoId"));
				netInfo.setIFrameInterval(getInteger(netNode, "iFrameInterval"));
				netInfo.setStreamType(getInteger(netNode, "streamType"));
				netInfos[i] = netInfo;
			}
			infos.setNets(netInfos);
		}

		ImageParameterInfo recInfo = new ImageParameterInfo();
		recInfo.setBitRate(getInteger(parameters, "rec/bitRate"));
		recInfo.setBitRateType(getInteger(parameters, "rec/bitRateType"));
		recInfo.setFlag(getInteger(parameters, "rec/flag"));
		recInfo.setFrameRate(getInteger(parameters, "rec/frameRate"));
		recInfo.setImageSize(getString(parameters, "rec/imageSize"));
		recInfo.setPicQuality(getInteger(parameters, "rec/picQuality"));
		recInfo.setVideoId(getInteger(parameters, "rec/videoId"));
		recInfo.setIFrameInterval(getInteger(parameters, "rec/iFrameInterval"));
		recInfo.setStreamType(getInteger(parameters, "rec/streamType"));

		infos.setRec(recInfo);
		return infos;
	}

	public GPIODeviceInfo getInOutDev() {

		GetMethod method = new GetMethod("/GetVsInOutDev");
		Node parameters = this.executeGetMethod(method);

		GPIODeviceInfo deviceInfo = new GPIODeviceInfo();

		List list = parameters.selectNodes("input");
		if (list != null) {
			ChannelInfo[] input = new ChannelInfo[list.size()];
			for (int i = 0; i < input.length; i++) {
				Node channelInfo = (Node) list.get(i);
				input[i] = new ChannelInfo();
				input[i].setChannelNumber(getInteger(channelInfo,
						"channelNumber"));
				input[i].setState(getInteger(channelInfo, "state"));
			}
			deviceInfo.setInput(input);
		}

		list = parameters.selectNodes("output");
		if (list != null) {
			ChannelInfo[] output = new ChannelInfo[list.size()];
			for (int i = 0; i < output.length; i++) {
				Node channelInfo = (Node) list.get(i);
				output[i] = new ChannelInfo();
				output[i].setChannelNumber(getInteger(channelInfo,
						"channelNumber"));
				output[i].setState(getInteger(channelInfo, "state"));
			}
			deviceInfo.setOutput(output);
		}

		return deviceInfo;
	}

	public int getLastStatusCode() {
		return statusCode;
	}

	public NetworkCfgOut getNetworkInfo() {

		GetMethod method = new GetMethod("/GetVsIpInfo");
		Node parameters = this.executeGetMethod(method);

		NetworkCfgOut netCfg = new NetworkCfgOut();
		List list = parameters.selectNodes("ethernet");
		if (list != null) {
			Ethernet[] ethernet = new Ethernet[list.size()];
			for (int i = 0; i < ethernet.length; i++) {
				Node eth = (Node) list.get(i);
				ethernet[i] = new Ethernet();
				ethernet[i].setNetId(getInteger(eth, "netId"));
				ethernet[i].setIpAddress(getString(eth, "ipAddress"));
				ethernet[i].setNetMask(getString(eth, "subnetMask"));
				ethernet[i].setPort(getInteger(eth, "port"));
			}
			netCfg.setEthernet(ethernet);
		}

		list = parameters.selectNodes("dns");
		if (list != null) {
			String[] dns = new String[list.size()];
			for (int i = 0; i < dns.length; i++) {
				dns[i] = getString((Node) list.get(i), ".");
			}
			netCfg.setDns(dns);
		}

		list = parameters.selectNodes("gateway");
		if (list != null) {
			String[] gateway = new String[list.size()];
			for (int i = 0; i < gateway.length; i++) {
				gateway[i] = getString((Node) list.get(i), ".");
			}
			netCfg.setGateway(gateway);
		}

		return netCfg;
	}

	public PresetPTZ[] getPresetPTZ(int ptzId) {

		PresetPTZ[] presetPTZ = null;
		GetMethod method = new GetMethod("/GetPresetPTZ");
		NameValuePair[] pairs = new NameValuePair[] { new NameValuePair(
				"ptzId", String.valueOf(ptzId)) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);

		List list = parameters.selectNodes("preset");
		if (list != null) {
			presetPTZ = new PresetPTZ[list.size()];
			for (int i = 0; i < presetPTZ.length; i++) {
				Node preset = (Node) list.get(i);
				presetPTZ[i] = new PresetPTZ();
				presetPTZ[i].setPresetIndex(getInteger(preset, "presetIndex"));
				presetPTZ[i].setPresetName(getString(preset, "presetName"));
			}
		}

		return presetPTZ;
	}

	public SerialPortInfo getSerialPortInfo(int port) {

		GetMethod method = new GetMethod("/GetVsSerialPort");
		NameValuePair[] pairs = new NameValuePair[] { new NameValuePair("port",
				String.valueOf(port)) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);

		SerialPortInfo serialPort = new SerialPortInfo();
		serialPort.setPort(getInteger(parameters, "port"));
		serialPort.setBaudRate(getInteger(parameters, "baudRate"));
		serialPort.setDataBit(getInteger(parameters, "dataBit"));
		serialPort.setFlowcontrol(getInteger(parameters, "flowcontrol"));
		serialPort.setParity(getInteger(parameters, "parity"));
		serialPort.setStopBit(getInteger(parameters, "stopBit"));
		serialPort.setWorkMode(getInteger(parameters, "workMode"));

		return serialPort;

	}

	public TimeInfo getTime() {

		GetMethod method = new GetMethod("/GetVsTime");
		Node parameters = this.executeGetMethod(method);

		TimeInfo time = new TimeInfo();
		time.setYear(getInteger(parameters, "year"));
		time.setMonth(getInteger(parameters, "month"));
		time.setDate(getInteger(parameters, "date"));
		time.setHour(getInteger(parameters, "hour"));
		time.setMinute(getInteger(parameters, "minute"));
		time.setSecond(getInteger(parameters, "second"));

		return time;
	}

	public UserInfo[] getUser(String username) {

		UserInfo[] userInfo = null;
		GetMethod method = new GetMethod("/GetVsUser");
		NameValuePair[] pairs = new NameValuePair[] { new NameValuePair("name",
				username) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);

		List list = parameters.selectNodes("user");
		if (list != null) {
			userInfo = new UserInfo[list.size()];
			for (int i = 0; i < userInfo.length; i++) {
				Node user = (Node) list.get(i);
				userInfo[i] = new UserInfo();
				userInfo[i].setName(getString(user, "username"));
				userInfo[i].setPassword(getString(user, "password"));
			}
		}
		return userInfo;
	}

	public VideoInfo getVideoInfo(int videoId) {

		GetMethod method = new GetMethod("/GetVsVideo");
		NameValuePair[] pairs = new NameValuePair[] { new NameValuePair(
				"videoId", String.valueOf(videoId)) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);

		VideoInfo videoInfo = new VideoInfo();
		videoInfo.setVideoId(getInteger(parameters, "videoId"));
		videoInfo
				.setBitmapTimeEnable(getInteger(parameters, "bitmapTimeEnable"));
		Integer bitmapX = getInteger(parameters, "bitmapX");
		videoInfo.setBitmapX(bitmapX);
		Integer bitmapY = getInteger(parameters, "bitmapY");
		videoInfo.setBitmapY(bitmapY);
		videoInfo
				.setBitmapTextEnable(getInteger(parameters, "bitmapTextEnable"));
		videoInfo.setBitmapText(getString(parameters, "bitmapText"));
		Integer bitmapTextX = getInteger(parameters, "bitmapTextX");
		videoInfo.setBitmapTextX(bitmapTextX);
		Integer bitmapTextY = getInteger(parameters, "bitmapTextY");
		videoInfo.setBitmapTextY(bitmapTextY);

		return videoInfo;
	}

	public LocalStorageTask getVsLocalStorageTask(int videoId) {

		GetMethod method = new GetMethod("/GetVsLocalStorageTask");
		NameValuePair[] pairs = new NameValuePair[] { new NameValuePair(
				"videoId", String.valueOf(videoId)) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);

		LocalStorageTask task = new LocalStorageTask();
		task.setVideoId(getInteger(parameters, "videoId"));
		task.setRecordEnable(getInteger(parameters, "recordEnable"));
		task.setRecycleRecEnable(getInteger(parameters, "recycleRecEnable"));

		List list = parameters.selectNodes("schedule");
		if (list != null) {
			RecordSchedule[] schedule = new RecordSchedule[list.size()];
			for (int i = 0; i < schedule.length; i++) {
				Node sched = (Node) list.get(i);
				schedule[i] = new RecordSchedule();
				schedule[i]
						.setRecordType(getInteger(sched, "type") == null ? -1
								: getInteger(sched, "type").intValue());
				schedule[i]
						.setWeekday(getInteger(sched, "weekday") == null ? -1
								: getInteger(sched, "weekday").intValue());
				schedule[i]
						.setStartHour(getInteger(sched, "startHour") == null ? -1
								: getInteger(sched, "startHour").intValue());
				schedule[i]
						.setStartMin(getInteger(sched, "startMin") == null ? -1
								: getInteger(sched, "startMin").intValue());
				schedule[i]
						.setStopHour(getInteger(sched, "stopHour") == null ? -1
								: getInteger(sched, "stopHour").intValue());
				schedule[i]
						.setStopMin(getInteger(sched, "stopMin") == null ? -1
								: getInteger(sched, "stopMin").intValue());
			}
			task.setSchedule(schedule);
		}

		return task;
	}

	public DeviceStatistic getVsWorkState() {

		GetMethod method = new GetMethod("/GetVsWorkState");
		Node parameters = this.executeGetMethod(method);

		DeviceStatistic deviceStatistic = new DeviceStatistic();
		List list = parameters.selectNodes("disk");
		if (list != null) {
			DiskStatistic[] disk = new DiskStatistic[list.size()];
			for (int i = 0; i < disk.length; i++) {
				Node diskNode = (Node) list.get(i);
				disk[i] = new DiskStatistic();
				disk[i].setDiskId(getInteger(diskNode, "diskId"));
				disk[i].setTotalSize(getLong(diskNode, "totalSize"));
				disk[i].setFreeSize(getLong(diskNode, "freeSize"));
				disk[i].setStatus(getByte(diskNode, "status"));
			}
			deviceStatistic.setDisk(disk);
		}

		list = parameters.selectNodes("videoChannel");
		if (list != null) {
			VideoChannelStatistic[] video = new VideoChannelStatistic[list
					.size()];
			for (int i = 0; i < video.length; i++) {
				Node videoNode = (Node) list.get(i);
				video[i] = new VideoChannelStatistic();
				video[i].setBitRate(getInteger(videoNode, "bitRate"));
				video[i].setHardwareStatus(getByte(videoNode, "hardwareStatus"));
				video[i].setRecordStatus(getByte(videoNode, "recordStatus"));
				video[i].setCaptureStatus(getByte(videoNode, "captureStatus"));
				video[i].setSignalStatus(getByte(videoNode, "signalStatus"));
				video[i].setVideoId(getInteger(videoNode, "videoId"));
			}
			deviceStatistic.setVideo(video);
		}

		list = parameters.selectNodes("alarmIn");
		if (list != null) {
			byte[] alarmIn = new byte[list.size()];
			for (int i = 0; i < alarmIn.length; i++) {
				Node alarmInChannel = (Node) list.get(i);
				alarmIn[i] = getByte(alarmInChannel, "status") == null ? -1
						: getByte(alarmInChannel, "status").byteValue();
			}
			deviceStatistic.setAlarmIn(alarmIn);
		}

		list = parameters.selectNodes("alarmOut");
		if (list != null) {
			byte[] alarmOut = new byte[list.size()];
			for (int i = 0; i < alarmOut.length; i++) {
				Node alarmInChannel = (Node) list.get(i);
				alarmOut[i] = getByte(alarmInChannel, "status") == null ? -1
						: getByte(alarmInChannel, "status").byteValue();
			}
			deviceStatistic.setAlarmOut(alarmOut);
		}

		deviceStatistic.setDeviceStatus(getInteger(parameters, "deviceStatus"));
		deviceStatistic.setConnectionStatus(getString(parameters,
				"connectionStatus"));
		deviceStatistic.setRegisterStatus(getString(parameters,
				"registerStatus"));

		return deviceStatistic;
	}

	public void init() {

	}

	public boolean setVsAlarmConfiguration(AlarmConfiguration alarmCfg) {
		PostMethod method = new PostMethod("/SetVsAlarmConfiguration");
		if (alarmCfg.connectionDetectionEnabled) {
			method.addParameter("connectionDetectionEnabled", "true");
		}

		if (alarmCfg.diskFullAlarmEnabled) {
			method.addParameter("diskFullAlarmEnabled", "true");

		}
		if (alarmCfg.diskFullHighThreshold != null) {
			method.addParameter("diskFullHighThreshold",
					alarmCfg.diskFullHighThreshold.toString());
		}
		if (alarmCfg.diskFullLowThreshold != null) {
			method.addParameter("diskFullLowThreshold",
					alarmCfg.diskFullLowThreshold.toString());
		}
		if (alarmCfg.diskErrorAlarmEnabled) {
			method.addParameter("diskErrorAlarmEnabled", "true");
		}
		method.addParameter("photoResolution",
				String.valueOf(alarmCfg.photoResolution));
		method.addParameter("photoQuality",
				String.valueOf(alarmCfg.photoQuality));
		method.addParameter("shootTimes", String.valueOf(alarmCfg.shootTimes));
		if (null != alarmCfg.imageFormat) {
			method.addParameter("imageFormat", alarmCfg.imageFormat);
		}
		method.addParameter("alarmPreRecordTime",
				String.valueOf(alarmCfg.alarmPreRecordTime));
		method.addParameter("alarmRecordTime",
				String.valueOf(alarmCfg.alarmRecordTime));
		method.addParameter("alarmOutputTime",
				String.valueOf(alarmCfg.alarmOutputTime));

		AlarmConfiguration.GPINAlarm[] gpinAlarm = alarmCfg.gpinAlarm;
		for (int i = 0; gpinAlarm != null && i < gpinAlarm.length; i++) {
			if (gpinAlarm[i].gpinAlarmEnable) {
				method.addParameter("gpinAlarmEnabled",
						gpinAlarm[i].channelNumber + ",true");
				method.addParameter("gpinAlarmStatus",
						gpinAlarm[i].channelNumber + ","
								+ gpinAlarm[i].gpinAlarmStatus);
				AlarmConfiguration.AlarmOutput[] alarmOutput = gpinAlarm[i].gpinAlarmOutput;
				for (int j = 0; alarmOutput != null && j < alarmOutput.length; j++) {
					method.addParameter("gpinAlarmOutput",
							gpinAlarm[i].channelNumber + ","
									+ alarmOutput[j].channelNumber + ","
									+ alarmOutput[j].alarmState);
				}
				int[] alarmRec = gpinAlarm[i].gpinAlarmRecord;
				for (int k = 0; alarmRec != null && k < alarmRec.length; k++) {
					method.addParameter("gpinAlarmRecord",
							gpinAlarm[i].channelNumber + "," + alarmRec[k]);
				}
				int[] alarmShoot = gpinAlarm[i].gpinAlarmShoot;
				for (int j = 0; alarmShoot != null && j < alarmShoot.length; j++) {
					method.addParameter("gpinAlarmShoot",
							gpinAlarm[i].channelNumber + "," + alarmShoot[j]);
				}

			}
		}

		AlarmConfiguration.VideoAlarm[] videoAlarm = alarmCfg.videoAlarm;
		MessageFormat fmt = new MessageFormat(
				"{0,number,00}{1,number,00}-{2,number,00}{3,number,00}");
		for (int i = 0; videoAlarm != null && i < videoAlarm.length; i++) {
			if (videoAlarm[i].hideDetectionAlarmEnabled) {
				method.addParameter("hideDetectionAlarmEnabled",
						videoAlarm[i].videoId + ",true");
				Integer[] alarmSchedule = new Integer[] {
						new Integer(
								videoAlarm[i].hideDetectionAlarmTime
										.getStartHour()),
						new Integer(
								videoAlarm[i].hideDetectionAlarmTime
										.getStartMin()),
						new Integer(
								videoAlarm[i].hideDetectionAlarmTime
										.getStopHour()),
						new Integer(
								videoAlarm[i].hideDetectionAlarmTime
										.getStopMin()) };
				method.addParameter("hideDetectionAlarmTime",
						videoAlarm[i].videoId + "," + fmt.format(alarmSchedule));
				method.addParameter("hideDetectionX", videoAlarm[i].videoId
						+ "," + videoAlarm[i].hideDetectionX);
				method.addParameter("hideDetectionY", videoAlarm[i].videoId
						+ "," + videoAlarm[i].hideDetectionY);
				method.addParameter("hideDetectionWidth", videoAlarm[i].videoId
						+ "," + videoAlarm[i].hideDetectionWidth);
				method.addParameter("hideDetectionHeight",
						videoAlarm[i].videoId + ","
								+ videoAlarm[i].hideDetectionHeight);
				AlarmConfiguration.AlarmOutput[] alarmOutput = videoAlarm[i].hideDetectionAlarmOutput;
				for (int j = 0; alarmOutput != null && j < alarmOutput.length; j++) {
					method.addParameter("hideDetectionAlarmOutput",
							videoAlarm[i].videoId + ","
									+ alarmOutput[j].channelNumber + ","
									+ alarmOutput[j].alarmState);
				}
			}
			if (videoAlarm[i].videoLoseAlarmEnabled) {
				method.addParameter("videoLoseAlarmEnabled",
						videoAlarm[i].videoId + ",true");
				AlarmConfiguration.AlarmOutput[] alarmOutput = videoAlarm[i].videoLoseAlarmOutput;
				for (int j = 0; alarmOutput != null && j < alarmOutput.length; j++) {
					method.addParameter("videoLoseAlarmOutput",
							videoAlarm[i].videoId + ","
									+ alarmOutput[j].channelNumber + ","
									+ alarmOutput[j].alarmState);
				}
			}
			if (videoAlarm[i].motionDetectionAlarmEnabled) {
				method.addParameter("motionDetectionAlarmEnabled",
						videoAlarm[i].videoId + ",true");
				StringBuffer blocks = new StringBuffer();
				for (int j = 0; videoAlarm[i].motionDetectionBlocks != null
						&& j < videoAlarm[i].motionDetectionBlocks.length; j++) {
					blocks.append(videoAlarm[i].motionDetectionBlocks[j]);
				}
				method.addParameter("motionDetectionBlocks",
						videoAlarm[i].videoId + "," + blocks);
				method.addParameter("motionDetectionFrequency",
						videoAlarm[i].videoId + ","
								+ videoAlarm[i].motionDetectionFrequency);
				method.addParameter("motionDetectionSensitivity",
						videoAlarm[i].videoId + ","
								+ videoAlarm[i].motionDetectionSensitivity);
				for (int j = 0; videoAlarm[i].motionDetectionAlarmRecord != null
						&& j < videoAlarm[i].motionDetectionAlarmRecord.length; j++) {
					method.addParameter(
							"motionDetectionAlarmRecord",
							videoAlarm[i].videoId
									+ ","
									+ videoAlarm[i].motionDetectionAlarmRecord[j]);
				}
				Integer[] alarmSchedule = new Integer[] {
						new Integer(
								videoAlarm[i].motionDetectionAlarmTime
										.getStartHour()),
						new Integer(
								videoAlarm[i].motionDetectionAlarmTime
										.getStartMin()),
						new Integer(
								videoAlarm[i].motionDetectionAlarmTime
										.getStopHour()),
						new Integer(
								videoAlarm[i].motionDetectionAlarmTime
										.getStopMin()) };
				method.addParameter("motionDetectionAlarmTime",
						videoAlarm[i].videoId + "," + fmt.format(alarmSchedule));
				AlarmConfiguration.AlarmOutput[] alarmOutput = videoAlarm[i].motionDetectionAlarmOutput;
				for (int j = 0; alarmOutput != null && j < alarmOutput.length; j++) {
					method.addParameter("motionDetectionAlarmOutput",
							videoAlarm[i].videoId + ","
									+ alarmOutput[j].channelNumber + ","
									+ alarmOutput[j].alarmState);
				}
				for (int m = 0; videoAlarm[i].motionDetectionAlarmShoot != null
						&& m < videoAlarm[i].motionDetectionAlarmShoot.length; m++) {
					method.addParameter(
							"motionDetectionAlarmShoot",
							videoAlarm[i].videoId
									+ ","
									+ videoAlarm[i].motionDetectionAlarmShoot[m]);
				}
			}
		}

		AlarmConfiguration.GPOUTAlarm[] gpoutAlarm = alarmCfg.gpoutAlarm;
		for (int i = 0; gpoutAlarm != null && i < gpoutAlarm.length; i++) {
			method.addParameter("gpoutDeviceName", gpoutAlarm[i].channelNumber
					+ "," + gpoutAlarm[i].gpoutDeviceName);
			method.addParameter("gpoutType", gpoutAlarm[i].channelNumber + ","
					+ gpoutAlarm[i].gpoutType);
			method.addParameter(
					"gpoutActivatedTime",
					gpoutAlarm[i].channelNumber
							+ ","
							+ fmt.format(new Integer[] {
									new Integer(
											gpoutAlarm[i].gpoutActivatedTime
													.getStartHour()),
									new Integer(
											gpoutAlarm[i].gpoutActivatedTime
													.getStartMin()),
									new Integer(
											gpoutAlarm[i].gpoutActivatedTime
													.getStopHour()),
									new Integer(
											gpoutAlarm[i].gpoutActivatedTime
													.getStopMin()) }));
		}

		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public DiskSizeInfo[] queryVsLocalDisk() {

		GetMethod method = new GetMethod("/QueryVsLocalDisk");
		Node parameters = this.executeGetMethod(method);

		DiskSizeInfo[] diskSizeInfo = null;
		List list = parameters.selectNodes("disk");
		if (list != null) {
			diskSizeInfo = new DiskSizeInfo[list.size()];
			for (int i = 0; i < diskSizeInfo.length; i++) {
				Node diskNode = (Node) list.get(i);
				diskSizeInfo[i] = new DiskSizeInfo();
				diskSizeInfo[i].setDiskId(getInteger(diskNode, "diskId"));
				diskSizeInfo[i].setTotalSize(getLong(diskNode, "totalSize"));
				diskSizeInfo[i].setFreeSize(getLong(diskNode, "freeSize"));
			}
		}
		return diskSizeInfo;
	}

	public RecordFile[] queryVsLocalStorageFiles(StorageQuery query) {

		GetMethod method = new GetMethod("/QueryVsLocalStorageFiles");
		method.setQueryString(new NameValuePair[] {
				new NameValuePair("videoId", query.getVideoId().toString()),
				new NameValuePair("fileType", query.getFileType().toString()),
				new NameValuePair("startTime", query.getStartTime().replaceAll(
						" ", "%20")),
				new NameValuePair("endTime", query.getEndTime().replaceAll(" ",
						"%20")) });

		Node parameters = this.executeGetMethod(method);

		RecordFile[] recordFile = null;
		List list = parameters.selectNodes("file");
		if (list != null) {
			recordFile = new RecordFile[list.size()];
			for (int i = 0; i < recordFile.length; i++) {
				Node fileNode = (Node) list.get(i);
				recordFile[i] = new RecordFile();
				recordFile[i].setFilename(getString(fileNode, "filename"));
				recordFile[i].setSize(getString(fileNode, "size"));
				recordFile[i].setStartTime(getString(fileNode, "startTime"));
				recordFile[i].setStopTime(getString(fileNode, "stopTime"));
			}
		}

		return recordFile;
	}

	public DeviceInfo requestVsDeviceInfo() {

		GetMethod method = new GetMethod("/RequestVsDeviceInfo");
		Node parameters = this.executeGetMethod(method);

		DeviceInfo deviceInfo = new DeviceInfo();
		deviceInfo.setSoftWareVersion(getString(parameters, "softWareVersion"));

		return deviceInfo;
	}

	public void requestVsUpgrade(String fileURL, int timeout, String deviceId) {
		GetMethod method = null;
		if (VssConstants.FRONT_TYPE_VS.equals(access.frontType)) {
			method = new GetMethod("/RequestVsUpgrade");
			method.setQueryString(new NameValuePair[] {
					new NameValuePair("fileURL", fileURL),
					new NameValuePair("timeout", String.valueOf(timeout * 60)),
					new NameValuePair("deviceId", deviceId) });
		} else if (VssConstants.FRONT_TYPE_AH.equals(access.frontType)) {
			method = new GetMethod("/RequestAhUpgrade");
			method.setQueryString(new NameValuePair[] {
					new NameValuePair("fileURL", fileURL),
					new NameValuePair("timeout", String.valueOf(timeout * 60)),
					new NameValuePair("deviceId", deviceId),
					new NameValuePair("loginName", access.vsLoginUsername),
					new NameValuePair("loginPassword", access.vsLoginPassword) });
		}

		Node parameters = this.executeGetMethod(method);
		String softWareVersion = getString(parameters, "softWareVersion");

		VsUpgradeThread vsUpgrade = new VsUpgradeThread(this.access);
		vsUpgrade.setTimeout(timeout);
		vsUpgrade.setBeforeUpgradeVersion(softWareVersion);
		synchronized (VsUpgradeThread.VS_UPGRADE_JOBS) {
			VsUpgradeThread.VS_UPGRADE_JOBS.put(deviceId, vsUpgrade);
		}

		vsUpgrade.setDaemon(true);
		vsUpgrade.start();

		return;
	}

	public boolean setDecoderCfg(SerialPortInfo serialPortInfo) {
		BeanValidator.validateNotNull(serialPortInfo, new String[] { "videoId",
				"decoderAddress", "decoderType" });
		GetMethod method = new GetMethod("/SetVsSerialPort");
		method.setQueryString(new NameValuePair[] {
				new NameValuePair("port", serialPortInfo.getPort().toString()),
				new NameValuePair("baudRate", serialPortInfo.getBaudRate()
						.toString()),
				new NameValuePair("dataBit", serialPortInfo.getDataBit()
						.toString()),
				new NameValuePair("parity", serialPortInfo.getParity()
						.toString()),
				new NameValuePair("stopBit", serialPortInfo.getStopBit()
						.toString()),
				new NameValuePair("flowcontrol", serialPortInfo
						.getFlowcontrol() == null ? "" : serialPortInfo
						.getFlowcontrol().toString()),
				new NameValuePair("decoderType", serialPortInfo
						.getDecoderType() == null ? "" : serialPortInfo
						.getDecoderType().toString()),
				new NameValuePair("decoderAddress", serialPortInfo
						.getDecoderAddress() == null ? "" : serialPortInfo
						.getDecoderAddress().toString()),
				// new NameValuePair("mode", serialPortInfo.getMode()),
				// new NameValuePair("timeout", serialPortInfo.getTimeout()),
				new NameValuePair("videoId", serialPortInfo.getVideoId()
						.toString()) });
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean setImageAdjustingInfo(ImageAdjustingInfo imgInfo) {

		GetMethod method = new GetMethod("/SetVsImageAdjusting");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("videoId", imgInfo.getVideoId().toString()),
				new NameValuePair("contrast", imgInfo.getContrast().toString()),
				new NameValuePair("bright", imgInfo.getBright().toString()),
				new NameValuePair("hue", imgInfo.getHue().toString()),
				new NameValuePair("saturation", imgInfo.getSaturation()
						.toString()),
		// new NameValuePair("ptzid", imgInfo.ptzId)
		};
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean setImageFormat(VideoFormat format) {

		/**
		 * BeanValidator.validateNotNull(format, "mode"); GetMethod method = new
		 * GetMethod("/SetVsImageFormat"); NameValuePair[] pairs = new
		 * NameValuePair[] { new NameValuePair("mode",
		 * format.getMode().toLowerCase()) }; method.setQueryString(pairs);
		 * String code = executeSetMethod(method); return
		 * SUCCESS_CODE.equals(code);
		 */
		return false;
	}

	public boolean setImageParameterInfo(ImageParameterInfo imgParams) {

		GetMethod method = new GetMethod("/SetVsImageParameters");

		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("videoId", imgParams.getVideoId().toString()),
				new NameValuePair("picQuality", imgParams.getPicQuality()
						.toString()),
				new NameValuePair("bitRate", imgParams.getBitRate().toString()),
				new NameValuePair("bitRateType",
						imgParams.getBitRateType() == null ? "" : imgParams
								.getBitRateType().toString()),
				new NameValuePair("frameRate", imgParams.getFrameRate()
						.toString()),
				new NameValuePair("imageSize", imgParams.getImageSize()),
				new NameValuePair("flag", imgParams.getFlag() == null ? ""
						: imgParams.getFlag().toString()),
				new NameValuePair("iFrameInterval", imgParams
						.getIFrameInterval().toString()),
				new NameValuePair("streamType", imgParams.getStreamType()
						.toString()) };
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean setImageParameterInfo_3N(ImageParameterInfo imgParams) {

		GetMethod method = new GetMethod("/SetVsImageParameters");

		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("videoId", imgParams.getVideoId().toString()),
				new NameValuePair("picQuality", imgParams.getPicQuality()
						.toString()),
				new NameValuePair("bitRate", imgParams.getBitRate().toString()),
				new NameValuePair("bitRateType",
						imgParams.getBitRateType() == null ? "" : imgParams
								.getBitRateType().toString()),
				new NameValuePair("frameRate", imgParams.getFrameRate()
						.toString()),
				new NameValuePair("imageSize", imgParams.getImageSize()),
				new NameValuePair("flag", imgParams.getFlag().toString()),
				new NameValuePair("subStreamId",
						imgParams.getSubStreamId() == null ? "" : imgParams
								.getSubStreamId().toString()),
				new NameValuePair("iFrameInterval", imgParams
						.getIFrameInterval().toString()),
				new NameValuePair("streamType",
						imgParams.getStreamType() == null ? "" : imgParams
								.getStreamType().toString()) };
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean setInOutDev(ChannelInfo channelInfo) {

		GetMethod method = new GetMethod("/SetVsInOutDev");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("channelNumber", channelInfo
						.getChannelNumber().toString()),
				new NameValuePair("state", channelInfo.getState().toString()),
				new NameValuePair("isInputChannel", String.valueOf(channelInfo
						.getChannelType()))

		};
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);

	}

	public boolean setNetworkInfo(NetworkCfgIn networkCfg) {

		String[] dns = { "", "", "" };
		String[] netDns = networkCfg.getDns();
		for (int i = 0; netDns != null && i < dns.length && i < netDns.length; i++) {
			dns[i] = netDns[i];
		}

		String[] gateway = { "" };
		String[] netGateway = networkCfg.getGateway();
		for (int i = 0; netGateway != null && i < gateway.length
				&& i < netGateway.length; i++) {
			gateway[i] = netGateway[i];
		}
		GetMethod method = new GetMethod("/InitVsIpInfo");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("netId", networkCfg.getNetId().toString()),
				new NameValuePair("ipAddress", networkCfg.getIpAddress()),
				new NameValuePair("subnetMask", networkCfg.getSubnetMask()),
				new NameValuePair("dns", dns[0]),
				new NameValuePair("dns", dns[1]),
				new NameValuePair("dns", dns[2]),
				new NameValuePair("gateway", gateway[0]),
				new NameValuePair("port", networkCfg.getPort().toString()) };
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean setPresetPTZ(PresetPTZ preset) {

		GetMethod method = new GetMethod("/SetPresetPTZ");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("ptzId", preset.getPtzId().toString()),
				new NameValuePair("presetIndex", preset.getPresetIndex()
						.toString()),
				new NameValuePair("presetName",
						preset.getPresetName() == null ? "" : preset
								.getPresetName().toString()) };
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);

	}

	public boolean setSerialPortInfo(SerialPortInfo serialPortInfo) {

		GetMethod method = new GetMethod("/SetVsSerialPort");
		method.setQueryString(new NameValuePair[] {
				new NameValuePair("port", serialPortInfo.getPort().toString()),
				new NameValuePair("baudRate", serialPortInfo.getBaudRate()
						.toString()),
				new NameValuePair("dataBit", serialPortInfo.getDataBit()
						.toString()),
				new NameValuePair("parity", serialPortInfo.getParity()
						.toString()),
				new NameValuePair("stopBit", serialPortInfo.getStopBit()
						.toString()),
				new NameValuePair("workMode",
						serialPortInfo.getWorkMode() == null ? ""
								: serialPortInfo.getWorkMode().toString())

		});
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean setTime(TimeInfo timeInfo) {

		GetMethod method = new GetMethod("/SetVsTime");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("hour", timeInfo.getHour().toString()),
				new NameValuePair("minute", timeInfo.getMinute().toString()),
				new NameValuePair("second", timeInfo.getSecond().toString()),
				new NameValuePair("month", timeInfo.getMonth().toString()),
				new NameValuePair("date", timeInfo.getDate().toString()),
				new NameValuePair("year", timeInfo.getYear().toString()) };
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean setUser(UserInfo userInfo) {

		BeanValidator.validateNotNull(userInfo, new String[] { "name",
				"password" });
		GetMethod method = new GetMethod("/SetVsUser");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("name", userInfo.getName()),
				new NameValuePair("password", userInfo.getPassword()) };
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean setVideoInfo(VideoInfo videoInfo) {

		GetMethod method = new GetMethod("/SetVsVideo");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("videoId", videoInfo.getVideoId().toString()),
				new NameValuePair("bitmapX", videoInfo.getBitmapX().toString()),
				new NameValuePair("bitmapY", videoInfo.getBitmapY().toString()),
				new NameValuePair("bitmapTimeEnable", videoInfo
						.getBitmapTimeEnable().toString()),
				new NameValuePair("bitmapTextEnable", videoInfo
						.getBitmapTextEnable().toString()),
				new NameValuePair("bitmapText", videoInfo.getBitmapText()),
				new NameValuePair("bitmapTextX", videoInfo.getBitmapTextX()
						.toString()),
				new NameValuePair("bitmapTextY", videoInfo.getBitmapTextY()
						.toString()) };
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean setVsLocalStorageTask(LocalStorageTask storageTask) {

		DecimalFormat format = new DecimalFormat("00");

		RecordSchedule[] rschedule = storageTask.getSchedule();
		String[] schedule = new String[rschedule.length];
		if (rschedule != null) {
			for (int i = 0; i < rschedule.length; i++) {
				schedule[i] = rschedule[i].getRecordType() + ","
						+ rschedule[i].getWeekday() + ","
						+ getTimePattern(rschedule[i].getStartHour(), format)
						+ ","
						+ getTimePattern(rschedule[i].getStartMin(), format)
						+ ","
						+ getTimePattern(rschedule[i].getStopHour(), format)
						+ ","
						+ getTimePattern(rschedule[i].getStopMin(), format);
			}
		}
		GetMethod method = new GetMethod("/SetVsLocalStorageTask");
		List pairsList = new ArrayList();
		pairsList.add(new NameValuePair("videoId", storageTask.getVideoId()
				.toString()));
		// pairsList.add(new NameValuePair("recordEnable", storageTask
		// .getRecordEnable().toString()));
		pairsList.add(new NameValuePair("recycleRecEnable", storageTask
				.getRecycleRecEnable().toString()));
		pairsList.add(new NameValuePair("recordPolicy", storageTask
				.getRecordPolicy() == null ? "" : storageTask.getRecordPolicy()
				.toString()));
		pairsList.add(new NameValuePair("mpeg4Frame", storageTask
				.getMpeg4Frame() == null ? "" : storageTask.getMpeg4Frame()
				.toString()));
		pairsList.add(new NameValuePair("mjpegFrame", storageTask
				.getMjpegFrame() == null ? "" : storageTask.getMjpegFrame()
				.toString()));
		pairsList.add(new NameValuePair("filenameSuffix", storageTask
				.getFilenameSuffix()));
		for (int i = 0; i < schedule.length; i++) {
			pairsList.add(new NameValuePair("schedule", schedule[i]));
		}
		method.setQueryString((NameValuePair[]) pairsList
				.toArray(new NameValuePair[0]));
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean stopVsLocalStorageTask(int videoId, boolean isStop) {

		GetMethod method = new GetMethod("/StopVsLocalStorageTask");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("videoId", String.valueOf(videoId)),
				new NameValuePair("recordEnable", isStop ? "0" : "1") };
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public CameraHide getHideImageArea(int cameraNumber) {
		GetMethod method = new GetMethod("/GetHideImageArea");
		method.setQueryString(new NameValuePair[] { new NameValuePair(
				"cameraNumber", String.valueOf(cameraNumber)) });
		Node parametersNode = executeGetMethod(method);

		CameraHide cameraHide = new CameraHide();
		cameraHide.setCameraNumber(new Integer(cameraNumber));

		List hideImageAreaNodes = parametersNode.selectNodes("hideImageArea");
		List temp = new ArrayList();
		for (int i = 0; i < hideImageAreaNodes.size(); i++) {
			CameraHide.HideImageArea hideImageArea = cameraHide.new HideImageArea();
			hideImageArea.setX(getInteger((Node) hideImageAreaNodes.get(i), "x"));
			hideImageArea.setY(getInteger((Node) hideImageAreaNodes.get(i), "y"));
			hideImageArea.setHeight(getInteger((Node) hideImageAreaNodes.get(i), "height"));
			hideImageArea.setWidth(getInteger((Node) hideImageAreaNodes.get(i),"width"));
			temp.add(hideImageArea);
		}
		cameraHide.setHideImageAreas((HideImageArea[]) temp
				.toArray(new CameraHide.HideImageArea[0]));

		return cameraHide;
	}

	public boolean setHideImageArea(CameraHide cameraHide) {
		PostMethod method = new PostMethod("/SetHideImageArea");
		method.addParameter("cameraNumber", cameraHide.getCameraNumber()
				.toString());
		CameraHide.HideImageArea[] hideImageAreas = cameraHide
				.getHideImageAreas();
		for (int i = 0; i < hideImageAreas.length; i++) {
			method.addParameter("hideImageArea",
					hideImageAreas[i].getX() + "," + hideImageAreas[i].getY()
							+ "," + hideImageAreas[i].getWidth() + ","
							+ hideImageAreas[i].getHeight());
		}
		String resultCode = executeSetMethod(method);
		return SUCCESS_CODE.equals(resultCode);
	}

	public CruiseTrackInfo[] getCruiseTrackInfo(Integer ptzId,
			Integer cruiseNumber) {
		GetMethod method = new GetMethod("/GetCruiseTrack");
		NameValuePair[] pairs;
		if (cruiseNumber != null) {
			pairs = new NameValuePair[] {
					new NameValuePair("ptzId", String.valueOf(ptzId)),
					new NameValuePair("cruiseNumber",
							String.valueOf(cruiseNumber)) };
		} else {
			pairs = new NameValuePair[] { new NameValuePair("ptzId",
					String.valueOf(ptzId)) };
		}
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);
		List cruise = parameters.selectNodes("cruise");
		List cruiseTrackInfo = new ArrayList();
		if (cruise != null) {
			Iterator iterator = cruise.iterator();
			while (iterator.hasNext()) {
				Node item = (Node) iterator.next();
				CruiseTrackInfo cti = new CruiseTrackInfo();
				cti.setPtzId(ptzId);
				cti.setCruiseNumber(getInteger(item, "cruiseNumber"));
				List cruisePtInfs = item.selectNodes("cruisePoint");
				List cruisePts = new ArrayList();
				if (cruisePtInfs != null) {
					Iterator it = cruisePtInfs.iterator();
					while (it.hasNext()) {
						Node temp = (Node) it.next();
						CruisePointInfo ct = new CruisePointInfo();
						ct.setDwellTime(getInteger(temp, "dwellTime"));
						ct.setPresetIndex(getInteger(temp, "presetIndex"));
						ct.setSpeed(getInteger(temp, "speed"));
						cruisePts.add(ct);
					}
				}
				cti.setCruisePoints((CruisePointInfo[]) cruisePts
						.toArray(new CruisePointInfo[0]));
				cruiseTrackInfo.add(cti);
			}
		}
		return (CruiseTrackInfo[]) cruiseTrackInfo
				.toArray(new CruiseTrackInfo[0]);
	}

	public boolean setCruiseTrackInfo(CruiseTrackInfo cruiseTrackInfo) {
		GetMethod method = new GetMethod("/SetCruiseTrack");
		List nvps = new ArrayList();
		CruisePointInfo[] cruisePts = cruiseTrackInfo.getCruisePoints();
		for (int i = 0; i < cruisePts.length; i++) {
			CruisePointInfo item = cruisePts[i];
			NameValuePair nvp = new NameValuePair("cruisePoint",
					(item.getPresetIndex() + "," + item.getSpeed() + "," + item
							.getDwellTime()));
			nvps.add(nvp);
		}
		nvps.add(new NameValuePair("ptzId", "" + cruiseTrackInfo.getPtzId()));
		nvps.add(new NameValuePair("cruiseNumber", ""
				+ cruiseTrackInfo.getCruiseNumber()));
		method.setQueryString((NameValuePair[]) nvps
				.toArray(new NameValuePair[0]));
		String code = this.executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean setDeviceId(String id) {
		GetMethod method = new GetMethod("/InitDeviceId");
		NameValuePair[] nvp = new NameValuePair[] { new NameValuePair(
				"deviceId", id) };
		method.setQueryString(nvp);
		String code = this.executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public boolean transparentChannel(
			TransparentChannelInfo transparentChannelInfo) {
		GetMethod method = new GetMethod("/TransparentChannel");
		NameValuePair[] nvp = new NameValuePair[] {
				new NameValuePair("comNumber",
						transparentChannelInfo.getComNumber()),
				new NameValuePair("data", transparentChannelInfo.getData()) };
		method.setQueryString(nvp);
		String code = this.executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public VSCommon getVSCommon() {
		GetMethod method = new GetMethod("/GetVsCommonInfo");
		Node parametersNode = executeGetMethod(method);

		VSCommon vsCommon = new VSCommon();
		vsCommon.setDeviceId(getString(parametersNode, "deviceId"));
		vsCommon.setDeviceName(getString(parametersNode, "deviceName"));
		vsCommon.setVideoMonitorEnabled(getString(parametersNode,
				"videoMonitorEnabled"));
		vsCommon.setVideoMonitorInterval(getInteger(parametersNode,
				"videoMonitorInterval"));
		vsCommon.setPassWord(getString(parametersNode, "passWord"));
		return vsCommon;
	}

	public boolean setVSCommon(VSCommon commonInfo) {
		GetMethod method = new GetMethod("/SetVsCommonInfo");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("deviceId", commonInfo.getDeviceId()),
				new NameValuePair("deviceName", commonInfo.getDeviceName()),
				new NameValuePair("videoMonitorEnabled",
						commonInfo.getVideoMonitorEnabled()),
				new NameValuePair("videoMonitorInterval",
						commonInfo.getVideoMonitorInterval() == null ? ""
								: commonInfo.getVideoMonitorInterval()
										.toString()),
				new NameValuePair("passWord", commonInfo.getPassWord()) };
		method.setQueryString(pairs);
		String code = executeSetMethod(method);
		return SUCCESS_CODE.equals(code);
	}

	public NetManageInfo getNetManageInfo() {
		GetMethod method = new GetMethod("/GetNetManageInfo");
		Node parametersNode = executeGetMethod(method);

		NetManageInfo netManageInfo = new NetManageInfo();
		netManageInfo.setManagerServerIp(getString(parametersNode,
				"managerServerIp"));
		netManageInfo.setManagerServerPort(getInteger(parametersNode,
				"managerServerPort"));
		netManageInfo.setHeartBeatServerIp(getString(parametersNode,
				"heartBeatServerIp"));
		netManageInfo.setHeartBeatPort(getInteger(parametersNode,
				"heartBeatPort"));
		netManageInfo.setRegisterServerIp(getString(parametersNode,
				"registerServerIp"));
		netManageInfo
				.setRegisterPort(getInteger(parametersNode, "registerPort"));
		netManageInfo.setEnableHeartBeat(new Boolean(getString(parametersNode,
				"enableHeartBeat")));
		netManageInfo.setHeartBeatPeriod(getInteger(parametersNode,
				"heartBeatPeriod"));
		netManageInfo.setRegisterValidTime(getInteger(parametersNode,
				"registerValidTime"));
		netManageInfo.setVapPath(getString(parametersNode, "vapPath"));

		return netManageInfo;
	}

	public boolean setNetManageInfo(NetManageInfo netManageInfo) {
		PostMethod method = new PostMethod("/SetNetManageInfo");

		method.addParameters(new NameValuePair[] {
				new NameValuePair("managerServerIp", netManageInfo
						.getManagerServerIp()),
				new NameValuePair("managerServerPort", netManageInfo
						.getManagerServerPort() == null ? "" : netManageInfo
						.getManagerServerPort().toString()),
				new NameValuePair("heartBeatServerIp", netManageInfo
						.getHeartBeatServerIp()),
				new NameValuePair("heartBeatPort", netManageInfo
						.getHeartBeatPort() == null ? "" : netManageInfo
						.getHeartBeatPort().toString()),
				new NameValuePair("registerServerIp", netManageInfo
						.getRegisterServerIp()),
				new NameValuePair("registerPort", netManageInfo
						.getRegisterPort() == null ? "" : netManageInfo
						.getRegisterPort().toString()),
				new NameValuePair("enableHeartBeat", netManageInfo
						.getEnableHeartBeat() == null ? "" : netManageInfo
						.getEnableHeartBeat().toString()),
				new NameValuePair("heartBeatPeriod", netManageInfo
						.getHeartBeatPeriod() == null ? "" : netManageInfo
						.getHeartBeatPeriod().toString()),
				new NameValuePair("registerValidTime", netManageInfo
						.getRegisterValidTime() == null ? "" : netManageInfo
						.getRegisterValidTime().toString()),
				new NameValuePair("vapPath", netManageInfo.getVapPath()) });

		String statusCode = executeSetMethod(method);
		return SUCCESS_CODE.equals(statusCode);
	}

	public VideoPerformance getVsPerformance(String statisticTarget) {
		GetMethod method = new GetMethod("/GetVsPerformance");
		method.setQueryString(new NameValuePair[] { new NameValuePair(
				"statisticTarget", statisticTarget) });
		Node parameterNode = executeGetMethod(method);
		Node usageNode = parameterNode.selectSingleNode("usage");

		VideoPerformance videoPerformance = new VideoPerformance();
		videoPerformance.setCpu(getString(usageNode, "cpu"));
		videoPerformance.setMemory(getString(usageNode, "mem"));
		videoPerformance.setDisk(getString(usageNode, "disk"));
		videoPerformance.setTimestamp(getString(usageNode, "timestamp"));
		return videoPerformance;
	}

	@Override
	public boolean recordVideo(Integer[] videoIds, Integer duration) {
		// TODO Auto-generated method stub
		GetMethod method = new GetMethod("/RecordVideo");
		List pars = new ArrayList();
		for (int i = 0; i < videoIds.length; i++) {
			pars.add(new NameValuePair("videoId", videoIds[i].toString()));
		}
		pars.add(new NameValuePair("duration", duration.toString()));
		method.setQueryString((NameValuePair[]) pars
				.toArray(new NameValuePair[0]));
		String code = executeSetMethod(method);
		return true;
	}

	// //////////////////////////////////////////////////////////
	private Document executeMethodForDOM(HttpMethod method) {
		Document doc = null;
		try {
			if (log.isDebugEnabled()) {
				log.debug("###  >>> CSG -> VS REQUEST = " + method.getPath());
				log.debug("		>>> "+method.getQueryString());
			}
			
			statusCode = httpClient.executeMethod(method);
			if (statusCode == 401) {
				throw new VssException(VssConstants.CODE_VS_AUTHENTICATE_FAILED);
			}
			// byte[] b=method.getResponseBody();
			SAXReader reader = new SAXReader();
			// Document document =
			// reader.read(method.getResponseBodyAsStream());

			doc = reader.read(method.getResponseBodyAsStream());
		} catch (IOException e) {
			throw new VssException(VssConstants.CODE_VISIT_NVS_ERROR);
		} catch (DocumentException e) {
			throw new VssException(VssConstants.CODE_VS_RETURN_ERROR_RESULT);
		} finally {
			method.releaseConnection();
		}
		return doc;
	}

	private void excuteMethod(HttpMethod method) {
		try {
			statusCode = httpClient.executeMethod(method);
			if (statusCode == 401) {
				throw new VssException(VssConstants.CODE_VS_AUTHENTICATE_FAILED);
			}
		} catch (HttpException e) {
			throw new VssException(VssConstants.CODE_VISIT_NVS_ERROR);
		} catch (IOException e) {
			throw new VssException(VssConstants.CODE_VISIT_NVS_ERROR);
		} finally {
			method.releaseConnection();
		}

	}

	private Node executeGetMethod(HttpMethod method) {
		Document doc = this.executeMethodForDOM(method);
		String statusCode = doc.selectSingleNode(RETURN_CODE_PATH).getText();
		if (!SUCCESS_CODE.equals(statusCode)) {
			throw new VssException(VssConstants.CODE_VS_GET_COMMAND_FAILED);
		}
		return doc.selectSingleNode(PARAMETERS_PATH);
	}

	private String executeSetMethod(HttpMethod method) {
		Document doc = this.executeMethodForDOM(method);
		return doc.selectSingleNode(RETURN_CODE_PATH).getText();
	}

	private static String getString(Node node, String xpath) {
		String value = null;
		Node n = node.selectSingleNode(xpath);
		if (n != null)
			value = n.getText();
		return value;
	}

	private static Integer getInteger(Node node, String xpath) {
		Integer value = null;
		try {
			value = new Integer(getString(node, xpath));
		} catch (NumberFormatException e) {
			// logger.warn(xpath, e);
		}
		return value;
	}

	private static Long getLong(Node node, String xpath) {
		Long value = null;
		try {
			value = new Long(getString(node, xpath));
		} catch (NumberFormatException e) {
			// logger.warn(xpath, e);
		}
		return value;
	}

	private static Byte getByte(Node node, String xpath) {
		Byte value = null;
		try {
			value = new Byte(getString(node, xpath));
		} catch (NumberFormatException e) {
			logger.warn(xpath, e);
		}
		return value;
	}

	private static Boolean getBoolean(Node node, String xpath) {
		Boolean value = null;
		try {
			value = new Boolean(getString(node, xpath));
		} catch (NumberFormatException e) {
			logger.warn(xpath, e);
		}
		return value;
	}

	private String getTimePattern(int time, NumberFormat format) {
		String result = "";
		try {
			result = format.format(time);
		} catch (Exception e) {

		}
		return result;
	}

	public LogInfo[] getVsLog(LogRequest logRequest) {

		PostMethod method = new PostMethod("/GetLog");// get vs log
		method.addParameter(new NameValuePair("selectMode", logRequest
				.getSelectMode().toString()));
		if (logRequest.getMajorType() != null) {
			method.addParameter(new NameValuePair("majorType", logRequest
					.getMajorType().toString()));
		}
		if (logRequest.getMinorType() != null) {
			method.addParameter(new NameValuePair("minorType", logRequest
					.getMinorType().toString()));
		}
		if (logRequest.getStartTime() != null) {
			method.addParameter(new NameValuePair("startTime", logRequest
					.getStartTime().replaceAll(" ", "%20")));
		}
		if (logRequest.getStopTime() != null) {
			method.addParameter(new NameValuePair("stopTime", logRequest
					.getStopTime().replaceAll(" ", "%20")));
		}
		Node parameters = this.executeGetMethod(method);

		LogInfo[] logInfo = null;
		List list = parameters.selectNodes("log");
		if (list != null) {
			logInfo = new LogInfo[list.size()];
			for (int i = 0; i < logInfo.length; i++) {
				Node logNode = (Node) list.get(i);
				logInfo[i] = new LogInfo();
				logInfo[i].setMajorType(getInteger(logNode, "majorType"));
				logInfo[i].setMinorType(getInteger(logNode, "minorType"));
				logInfo[i].setLogTime(getString(logNode, "logTime"));
				logInfo[i].setLogData(getString(logNode, "logData"));

			}
		}
		return logInfo;
	}

	public AlarmConfiguration getVsAlarmConfiguration() {
		final String alarmConfiguration_diskFullAlarmEnabled = "//diskFullAlarmEnabled";
		final String alarmConfiguration_diskFullHighThreshold = "//diskFullHighThreshold";
		final String alarmConfiguration_diskFullLowThreshold = "//diskFullLowThreshold";
		final String alarmConfiguration_diskErrorAlarmEnabled = "//diskErrorAlarmEnabled";
		final String alarmConfiguration_alarmPreRecordTime = "//alarmPreRecordTime";
		final String alarmConfiguration_alarmRecordTime = "//alarmRecordTime";
		final String alarmConfiguration_alarmOutputTime = "//alarmOutputTime";
		final String alarmConfiguration_photoResolution = "//photoResolution";
		final String alarmConfiguration_photoQualit = "//photoQuality";
		final String alarmConfiguration_shootTimes = "//shootTimes";
		final String alarmConfiguration_imageFormat = "//imageFormat";
		// gpinAlarm
		//
		final String alarmConfiguration_gpinAlarm = "//gpinAlarm";

		// gpoutAlarm
		//
		final String alarmConfiguration_gpoutAlarm = "//gpoutAlarm";

		// cameraAlarm
		//
		final String alarmConfiguration_cameraAlarm = "//cameraAlarm";

		GetMethod method = new GetMethod("/GetVsAlarmConfiguration");
		Node parameters = this.executeGetMethod(method);
		AlarmConfiguration alarmConfiguration = new AlarmConfiguration();
		alarmConfiguration.connectionDetectionEnabled = true;
		alarmConfiguration.diskFullAlarmEnabled = getBoolean(parameters,
				alarmConfiguration_diskFullAlarmEnabled).booleanValue();
		alarmConfiguration.diskFullHighThreshold = getInteger(parameters,
				alarmConfiguration_diskFullHighThreshold);
		alarmConfiguration.diskFullLowThreshold = getInteger(parameters,
				alarmConfiguration_diskFullLowThreshold);
		alarmConfiguration.diskErrorAlarmEnabled = getBoolean(parameters,
				alarmConfiguration_diskErrorAlarmEnabled).booleanValue();
		alarmConfiguration.alarmPreRecordTime = getInteger(parameters,
				alarmConfiguration_alarmPreRecordTime).intValue();
		alarmConfiguration.alarmRecordTime = getInteger(parameters,
				alarmConfiguration_alarmRecordTime).intValue();
		alarmConfiguration.alarmOutputTime = getInteger(parameters,
				alarmConfiguration_alarmOutputTime).intValue();
		alarmConfiguration.photoResolution = getInteger(parameters,
				alarmConfiguration_photoResolution).intValue();
		alarmConfiguration.photoQuality = getInteger(parameters,
				alarmConfiguration_photoQualit).intValue();
		alarmConfiguration.shootTimes = getInteger(parameters,
				alarmConfiguration_shootTimes).intValue();
		alarmConfiguration.imageFormat = getString(parameters,
				alarmConfiguration_imageFormat);

		List gpinAlarm = parameters.selectNodes(alarmConfiguration_gpinAlarm);
		int count = 0;
		alarmConfiguration.gpinAlarm = new AlarmConfiguration.GPINAlarm[gpinAlarm
				.size()];
		for (Iterator iter = gpinAlarm.iterator(); iter.hasNext();) {
			Node element = (Node) iter.next();
			alarmConfiguration.gpinAlarm[count] = new AlarmConfiguration.GPINAlarm();
			alarmConfiguration.gpinAlarm[count].channelNumber = getInteger(
					element, "channelNumber");
			alarmConfiguration.gpinAlarm[count].gpinAlarmEnable = getBoolean(
					element, "gpinAlarmEnabled");
			alarmConfiguration.gpinAlarm[count].gpinAlarmStatus = getInteger(
					element, "gpinAlarmState");

			List gpinAlarm_gpinAlarmOutput = element
					.selectNodes("gpinAlarmOutput");
			int count_inner = 0;
			alarmConfiguration.gpinAlarm[count].gpinAlarmOutput = new AlarmConfiguration.AlarmOutput[gpinAlarm_gpinAlarmOutput
					.size()];
			for (Iterator iterator = gpinAlarm_gpinAlarmOutput.iterator(); iterator
					.hasNext();) {
				Node ele = (Node) iterator.next();
				alarmConfiguration.gpinAlarm[count].gpinAlarmOutput[count_inner] = new AlarmConfiguration.AlarmOutput();
				alarmConfiguration.gpinAlarm[count].gpinAlarmOutput[count_inner].alarmState = getInteger(
						ele, "alarmState");
				alarmConfiguration.gpinAlarm[count].gpinAlarmOutput[count_inner].channelNumber = getInteger(
						ele, "outputChannelNumber");
				count_inner++;

			}
			List gpinAlarm_gpinAlarmRecord = element
					.selectNodes("gpinAlarmRecord");
			count_inner = 0;
			alarmConfiguration.gpinAlarm[count].gpinAlarmRecord = new int[gpinAlarm_gpinAlarmRecord
					.size()];
			for (Iterator iterator = gpinAlarm_gpinAlarmRecord.iterator(); iterator
					.hasNext();) {
				Node ele = (Node) iterator.next();
				alarmConfiguration.gpinAlarm[count].gpinAlarmRecord[count_inner] = getInteger(
						ele, ".").intValue();
				count_inner++;

			}
			List gpinAlarm_gpinAlarmShoot = element
					.selectNodes("gpinAlarmShoot");
			count_inner = 0;
			alarmConfiguration.gpinAlarm[count].gpinAlarmShoot = new int[gpinAlarm_gpinAlarmShoot
					.size()];
			for (Iterator iterator = gpinAlarm_gpinAlarmShoot.iterator(); iterator
					.hasNext();) {
				Node ele = (Node) iterator.next();
				alarmConfiguration.gpinAlarm[count].gpinAlarmShoot[count_inner] = getInteger(
						ele, ".").intValue();
				count_inner++;

			}
			count++;
		}

		List gpoutAlarm = parameters.selectNodes(alarmConfiguration_gpoutAlarm);
		count = 0;
		alarmConfiguration.gpoutAlarm = new AlarmConfiguration.GPOUTAlarm[gpoutAlarm
				.size()];
		for (Iterator iter = gpoutAlarm.iterator(); iter.hasNext();) {
			Node element = (Node) iter.next();
			alarmConfiguration.gpoutAlarm[count] = new AlarmConfiguration.GPOUTAlarm();
			alarmConfiguration.gpoutAlarm[count].channelNumber = getInteger(
					element, "channelNumber").intValue();
			alarmConfiguration.gpoutAlarm[count].gpoutDeviceName = getString(
					element, "gpoutDeviceName");
			alarmConfiguration.gpoutAlarm[count].gpoutType = getInteger(
					element, "gpoutType").intValue();

			String temp = getString(element, "gpoutActivatedTime");
			alarmConfiguration.gpoutAlarm[count].gpoutActivatedTime = new Schedule();
			alarmConfiguration.gpoutAlarm[count].gpoutActivatedTime
					.setStartHour(Integer.valueOf(temp.substring(0, 2)));
			alarmConfiguration.gpoutAlarm[count].gpoutActivatedTime
					.setStartMin(Integer.valueOf(temp.substring(2, 4)));
			alarmConfiguration.gpoutAlarm[count].gpoutActivatedTime
					.setStopHour(Integer.valueOf(temp.substring(5, 7)));
			alarmConfiguration.gpoutAlarm[count].gpoutActivatedTime
					.setStopMin(Integer.valueOf(temp.substring(7, 9)));
			count++;
		}
		List cameraAlarm = parameters
				.selectNodes(alarmConfiguration_cameraAlarm);
		count = 0;
		alarmConfiguration.videoAlarm = new AlarmConfiguration.VideoAlarm[cameraAlarm
				.size()];
		for (Iterator iter = cameraAlarm.iterator(); iter.hasNext();) {
			Node element = (Node) iter.next();
			alarmConfiguration.videoAlarm[count] = new AlarmConfiguration.VideoAlarm();
			alarmConfiguration.videoAlarm[count].videoId = getInteger(element,
					"cameraNumber").intValue();
			alarmConfiguration.videoAlarm[count].videoLoseAlarmEnabled = getBoolean(
					element, "videoLoseAlarmEnabled").booleanValue();
			List cameraAlarm_videoLoseAlarmOutput = element
					.selectNodes("videoLoseAlarmOutput");
			int count_inner = 0;
			alarmConfiguration.videoAlarm[count].videoLoseAlarmOutput = new AlarmConfiguration.AlarmOutput[cameraAlarm_videoLoseAlarmOutput
					.size()];
			for (Iterator iterator = cameraAlarm_videoLoseAlarmOutput
					.iterator(); iterator.hasNext();) {
				Node ele = (Node) iterator.next();
				alarmConfiguration.videoAlarm[count].videoLoseAlarmOutput[count_inner] = new AlarmConfiguration.AlarmOutput();
				alarmConfiguration.videoAlarm[count].videoLoseAlarmOutput[count_inner].channelNumber = getInteger(
						ele, "outputChannelNumber");
				alarmConfiguration.videoAlarm[count].videoLoseAlarmOutput[count_inner].alarmState = getInteger(
						ele, "alarmState");
				count_inner++;
			}
			alarmConfiguration.videoAlarm[count].hideDetectionAlarmEnabled = getBoolean(
					element, "hideDetectionAlarmEnabled").booleanValue();
			String temp = getString(element, "hideDetectionAlarmTime");
			alarmConfiguration.videoAlarm[count].hideDetectionAlarmTime = new Schedule();
			alarmConfiguration.videoAlarm[count].hideDetectionAlarmTime
					.setStartHour(Integer.valueOf(temp.substring(0, 2)));
			alarmConfiguration.videoAlarm[count].hideDetectionAlarmTime
					.setStartMin(Integer.valueOf(temp.substring(2, 4)));
			alarmConfiguration.videoAlarm[count].hideDetectionAlarmTime
					.setStopHour(Integer.valueOf(temp.substring(5, 7)));
			alarmConfiguration.videoAlarm[count].hideDetectionAlarmTime
					.setStopMin(Integer.valueOf(temp.substring(7, 9)));
			alarmConfiguration.videoAlarm[count].hideDetectionX = getInteger(
					element, "hideDetectionX").intValue();
			alarmConfiguration.videoAlarm[count].hideDetectionY = getInteger(
					element, "hideDetectionY").intValue();
			alarmConfiguration.videoAlarm[count].hideDetectionWidth = getInteger(
					element, "hideDetectionWidth").intValue();
			alarmConfiguration.videoAlarm[count].hideDetectionHeight = getInteger(
					element, "hideDetectionHeight").intValue();
			List cameraAlarm_hideDetectionAlarmOutput = element
					.selectNodes("hideDetectionAlarmOutput");
			count_inner = 0;
			alarmConfiguration.videoAlarm[count].hideDetectionAlarmOutput = new AlarmConfiguration.AlarmOutput[cameraAlarm_hideDetectionAlarmOutput
					.size()];
			for (Iterator iterator = cameraAlarm_hideDetectionAlarmOutput
					.iterator(); iterator.hasNext();) {
				Node ele = (Node) iterator.next();
				alarmConfiguration.videoAlarm[count].hideDetectionAlarmOutput[count_inner] = new AlarmConfiguration.AlarmOutput();
				alarmConfiguration.videoAlarm[count].hideDetectionAlarmOutput[count_inner].alarmState = getInteger(
						ele, "alarmState").intValue();
				alarmConfiguration.videoAlarm[count].hideDetectionAlarmOutput[count_inner].channelNumber = getInteger(
						ele, "outputChannelNumber").intValue();
				count_inner++;
			}
			alarmConfiguration.videoAlarm[count].motionDetectionAlarmEnabled = getBoolean(
					element, "motionDetectionAlarmEnabled").booleanValue();
			temp = getString(element, "motionDetectionAlarmTime");
			alarmConfiguration.videoAlarm[count].motionDetectionAlarmTime = new Schedule();
			alarmConfiguration.videoAlarm[count].motionDetectionAlarmTime
					.setStartHour(Integer.valueOf(temp.substring(0, 2)));
			alarmConfiguration.videoAlarm[count].motionDetectionAlarmTime
					.setStartMin(Integer.valueOf(temp.substring(2, 4)));
			alarmConfiguration.videoAlarm[count].motionDetectionAlarmTime
					.setStopHour(Integer.valueOf(temp.substring(5, 7)));
			alarmConfiguration.videoAlarm[count].motionDetectionAlarmTime
					.setStopMin(Integer.valueOf(temp.substring(7, 9)));

			Node cameraAlarm_motionDetectionBlocks = element
					.selectSingleNode("motionDetectionBlocks");
			String blocks = getString(cameraAlarm_motionDetectionBlocks, ".");
			StringReader stringReader = new StringReader(blocks);
			alarmConfiguration.videoAlarm[count].motionDetectionBlocks = new byte[blocks
					.length()];
			for (int i = 0; i < alarmConfiguration.videoAlarm[count].motionDetectionBlocks.length; i++) {
				try {
					alarmConfiguration.videoAlarm[count].motionDetectionBlocks[i] = Byte
							.parseByte(((char) stringReader.read()) + "");
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
			alarmConfiguration.videoAlarm[count].motionDetectionFrequency = getInteger(
					element, "motionDetectionFrequency").intValue();
			alarmConfiguration.videoAlarm[count].motionDetectionSensitivity = getInteger(
					element, "motionDetectionSensitivity").intValue();
			List cameraAlarm_motionDetectionAlarmOutput = element
					.selectNodes("motionDetectionAlarmOutput");
			count_inner = 0;
			alarmConfiguration.videoAlarm[count].motionDetectionAlarmOutput = new AlarmConfiguration.AlarmOutput[cameraAlarm_motionDetectionAlarmOutput
					.size()];
			for (Iterator iterator = cameraAlarm_motionDetectionAlarmOutput
					.iterator(); iterator.hasNext();) {
				Node ele = (Node) iterator.next();
				alarmConfiguration.videoAlarm[count].motionDetectionAlarmOutput[count_inner] = new AlarmConfiguration.AlarmOutput();
				alarmConfiguration.videoAlarm[count].motionDetectionAlarmOutput[count_inner].alarmState = getInteger(
						ele, "alarmState").intValue();
				alarmConfiguration.videoAlarm[count].motionDetectionAlarmOutput[count_inner].channelNumber = getInteger(
						ele, "outputChannelNumber").intValue();
				count_inner++;
			}
			List cameraAlarm_motionDetectionAlarmRecord = element
					.selectNodes("motionDetectionAlarmRecord");
			count_inner = 0;
			alarmConfiguration.videoAlarm[count].motionDetectionAlarmRecord = new int[cameraAlarm_motionDetectionAlarmRecord
					.size()];
			for (Iterator iterator = cameraAlarm_motionDetectionAlarmRecord
					.iterator(); iterator.hasNext();) {
				Node ele = (Node) iterator.next();
				alarmConfiguration.videoAlarm[count].motionDetectionAlarmRecord[count_inner] = getInteger(
						ele, ".").intValue();
				count_inner++;
			}
			List cameraAlarm_motionDetectionAlarmShoot = element
					.selectNodes("motionDetectionAlarmShoot");
			count_inner = 0;
			alarmConfiguration.videoAlarm[count].motionDetectionAlarmShoot = new int[cameraAlarm_motionDetectionAlarmShoot
					.size()];
			for (Iterator iterator = cameraAlarm_motionDetectionAlarmShoot
					.iterator(); iterator.hasNext();) {
				Node ele = (Node) iterator.next();
				alarmConfiguration.videoAlarm[count].motionDetectionAlarmShoot[count_inner] = getInteger(
						ele, ".").intValue();
				count_inner++;
			}

			count++;
		}
		return alarmConfiguration;
	}

	@Override
	public UploadPic getUploadPicture(String deviceId) {
		PostMethod post = new PostMethod("/GetUploadPictureConfig");
		NameValuePair[] pair = new NameValuePair[] { new NameValuePair(
				"deviceId", deviceId) };
		post.addParameters(pair);
		Node result = executeGetMethod(post);
		Node uploadURL = result.selectSingleNode("uploadURL");
		Node enableUploadPicture = result
				.selectSingleNode("enableUploadPicture");
		Node limitedAmount = result.selectSingleNode("limitedAmount");
		Node limitedResolution = result.selectSingleNode("limitedResolution");
		Node waitingTimeAfterfailure = result
				.selectSingleNode("waitingTimeAfterfailure");
		if (null == result || null == enableUploadPicture
				|| null == limitedAmount || null == limitedResolution
				|| null == waitingTimeAfterfailure) {
			throw new VssException(VssConstants.CODE_VS_GET_UPLOAD_PICTURE);
		}
		UploadPic up = new UploadPic();
		try {
			up.setUploadURL(uploadURL.getText().trim());
			up.setEnableUploadPicture(Boolean.valueOf(enableUploadPicture
					.getText()));
			up.setLimitedAmount(Integer.parseInt(limitedAmount.getText()));
			up.setLimitedResolution(Integer.parseInt(limitedResolution
					.getText()));
			up.setWaitingTimeAfterfailure(Integer
					.parseInt(waitingTimeAfterfailure.getText()));
		} catch (Exception e) {
			logger.warn("get param failed", e);
			throw new VssException(VssConstants.CODE_VS_GET_UPLOAD_PICTURE);
		}
		return up;

	}

	@Override
	public boolean setUploadPicture(UploadPic up) {
		// TODO Auto-generated method stub
		PostMethod post = new PostMethod("/SetUploadPictureConfig");
		NameValuePair[] pair = new NameValuePair[] {
				new NameValuePair("uploadURL", up.getUploadURL()),
				new NameValuePair("enableUploadPicture", String.valueOf(up
						.isEnableUploadPicture())),
				new NameValuePair("limitedAmount", String.valueOf(up
						.getLimitedAmount())),
				new NameValuePair("limitedResolution", String.valueOf(up
						.getLimitedResolution())),
				new NameValuePair("waitingTimeAfterfailure", String.valueOf(up
						.getWaitingTimeAfterfailure())), };
		post.addParameters(pair);
		String code = executeSetMethod(post);
		return SUCCESS_CODE.equals(code);
	}

	@Override
	public PTZRegress getPTZRegress(int ptzId) {
		PostMethod post = new PostMethod("/GetPTZRegress");
		NameValuePair[] nvps = new NameValuePair[] { new NameValuePair("ptzId",
				String.valueOf(ptzId)) };
		post.addParameters(nvps);
		Node result = executeGetMethod(post);
		boolean enableRegress = Boolean.valueOf(result.selectSingleNode(
				"enableRegress").getText());
		PTZRegress pr = new PTZRegress();
		pr.setEnableRegress(enableRegress);
		Node index = result.selectSingleNode("presetIndex");
		Node time = result.selectSingleNode("regressTime");
		Node name = result.selectSingleNode("presetName");
		if (null != index) {
			pr.setPresetIndex(Integer.valueOf(index.getText()));
		}
		if (null != time) {
			pr.setRegressTime(Integer.valueOf(time.getText()));
		}
		if (null != name) {
			pr.setPresetName(name.getText());
		}

		return pr;
	}

	@Override
	public boolean setPTZRegress(PTZRegress ptzregress) {
		PostMethod post = new PostMethod("/SetPTZRegress");
		NameValuePair[] nvps = new NameValuePair[] {
				new NameValuePair("ptzId",
						String.valueOf(ptzregress.getPtzId())),
				new NameValuePair("enableRegress", String.valueOf(ptzregress
						.isEnableRegress())),
				new NameValuePair("regressTime", String.valueOf(ptzregress
						.getRegressTime())),
				new NameValuePair("presetIndex", String.valueOf(ptzregress
						.getPresetIndex())),
				new NameValuePair("presetName", ptzregress.getPresetName()) };
		post.addParameters(nvps);
		String resultCode = executeSetMethod(post);
		return SUCCESS_CODE.equalsIgnoreCase(resultCode);
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	//
	//
	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	public AHInfo GetAlarmHostInfo() {
		PostMethod post = new PostMethod("/GetAlarmHostInfo");
		NameValuePair[] pair = new NameValuePair[] {
				new NameValuePair("deviceId", access.getVsDeviceId()),
				new NameValuePair("loginName", access.getVsLoginUsername()),
				new NameValuePair("loginPassword", access.getVsLoginPassword()),
				new NameValuePair("serverIp", access.getVsIp()),
				new NameValuePair("serverPort", Integer.toString(access
						.getVsPort())) };
		post.addParameters(pair);
		Node result = executeGetMethod(post);
		AHInfo ahInfo = parseAlarmHostResponse(result);
		return ahInfo;
	}

	private AHInfo parseAlarmHostResponse(Node result) {
		AHInfo ahInfo = new AHInfo();
		ahInfo.setDeviceId(result.selectSingleNode("//deviceId").getText());
		ahInfo.setServerIp(result.selectSingleNode("//serverIp").getText());
		ahInfo.setServerPort(result.selectSingleNode("//serverPort").getText());
		ahInfo.setDefenceStatus(Integer.parseInt(result.selectSingleNode(
				"//defenceStatus").getText()));
		Node startZone = result.selectSingleNode("//startZone");
		if (null != startZone) {
			ahInfo.setStartZone(Integer.parseInt(startZone.getText()));
		}
		Node endzone = result.selectSingleNode("//endZone");
		if (null != endzone) {
			ahInfo.setEndZone(Integer.parseInt(endzone.getText()));
		}
		List zones = result.selectNodes("//zoneStatus");
		AHInfo.ZoneStatus[] zoneStatus = new AHInfo.ZoneStatus[zones.size()];
		int count = 0;
		for (Iterator iter = zones.iterator(); iter.hasNext();) {
			Node element = (Node) iter.next();
			AHInfo.ZoneStatus az = new AHInfo.ZoneStatus();
			zoneStatus[count] = az;
			zoneStatus[count].setZoneNumber(Integer.parseInt(element
					.selectSingleNode("zoneNumber").getText()));
			zoneStatus[count].setDefenceStatus(Integer.parseInt(element
					.selectSingleNode("defenceStatus").getText()));
			Node subResult = element.selectSingleNode("subResult");
			Node alarmStatus = element.selectSingleNode("alarmStatus");
			if (null != subResult) {
				zoneStatus[count].setSubResult(Integer.parseInt(subResult
						.getText()));
			}
			if (null != alarmStatus) {
				zoneStatus[count].setAlarmStatus(Integer.parseInt(alarmStatus
						.getText()));
			}
			count++;
		}
		ahInfo.setZoneStatus(zoneStatus);
		return ahInfo;
	}

	public AHInfo SetAlarmHostInfo(AHInfo ahInfo) {
		PostMethod post = new PostMethod("/SetAlarmHostDefence");
		List nameValuePair = new ArrayList();
		nameValuePair
				.add(new NameValuePair("deviceId", access.getVsDeviceId()));
		nameValuePair.add(new NameValuePair("loginName", access
				.getVsLoginUsername()));
		nameValuePair.add(new NameValuePair("loginPassword", access
				.getVsLoginPassword()));
		nameValuePair.add(new NameValuePair("serverIp", access.getVsIp()));
		nameValuePair.add(new NameValuePair("serverPort", Integer
				.toString(access.getVsPort())));
		nameValuePair.add(new NameValuePair("defenceStatus", Integer
				.toString(ahInfo.getDefenceStatus())));
		AHInfo.ZoneStatus[] zoneStatus = ahInfo.getZoneStatus();
		if (null != zoneStatus) {
			for (int i = 0; i < zoneStatus.length; i++) {
				// nameValuePair.add(new
				// NameValuePair("alarmStatus",zoneStatus[i].getZoneNumber()+","+zoneStatus[i].getAlarmStatus()));
				nameValuePair.add(new NameValuePair("zoneStatus", zoneStatus[i]
						.getZoneNumber()
						+ ","
						+ zoneStatus[i].getDefenceStatus()));
			}
		}
		post.addParameters((NameValuePair[]) nameValuePair
				.toArray(new NameValuePair[0]));
		Node result = executeGetMethod(post);
		AHInfo ahInfoReturn = parseAlarmHostResponse(result);
		return ahInfoReturn;
	}

	@Override
	public String requestAhDeviceInfo(String deviceId) {
		// TODO Auto-generated method stub

		GetMethod method = new GetMethod("/RequestAhDeviceInfo");
		NameValuePair[] pairs = new NameValuePair[] {
				new NameValuePair("deviceId", access.vsDeviceId),
				new NameValuePair("loginName", access.vsLoginUsername),
				new NameValuePair("loginPassword", access.vsLoginPassword) };
		method.setQueryString(pairs);
		Node parameters = this.executeGetMethod(method);
		return getString(parameters, "softWareVersion");

	}

}
